<?php
namespace Admin\Controller;

vendor('grafika.autoloader');
use Grafika\Curl;

class LiveController extends BaseController {

    public  $live_status;
    /*
     * 初始化操作
     */
    public function _initialize() {
        parent::_initialize();
        $this->live_status = C('WECHAT_LIVE_STATUS');
        $this->assign('live_status',$this->live_status);
    }

    public function live_list(){

        getWechatLive();

        $keywords = I('keywords',false);
        if($keywords){
            $where = "name like '%$keywords%' ";
        }

        $count = M('live')->where($where)->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
        $list = M('live')->where($where)->order('roomid desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        $show = $Page->show();// 分页显示输出
        $this->assign('list',$list);// 赋值数据集
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }



    public function video_list()
    {
        $video =  M('video');

        $keywords = I('keywords',false);
        if($keywords){
            $where = "name like '%$keywords%'" ;
        }
        $count = $video->where($where)->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
        $res = $video->where($where)->order('sort desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        foreach ($res as $key=>$re){
            $res[$key]['qrcode'] = '/'.QRCODE_VIDEO_PATH.'/'.md5($re['id']).'.jpg';
        }

        $show = $Page->show();// 分页显示输出
        $this->assign('list',$res);// 赋值数据集
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }


    public function video()
    {
        $act = I('GET.act','add');
        $id = I('GET.id');
        if($id){
            $info = M('video')->where('id='.$id)->find();
        }
        $this->assign('info',$info);
        $this->assign('act',$act);
        $this->assign('feedIdPng','/Public/images/finderUserHelp.png');
        $this->assign('feedIdHelpPng','/Public/images/video_help.png');
        $this->display();
    }

    public function videoHandle()
    {
        $data = I('post.');

        if($data['act'] == 'del'){
            $r = M('video')->where('id='.$data['del_id'])->delete();
            if($r) exit(json_encode(1));
        }

        if(!$data['name'] || !$data['feedid']){
            $this->error("必填信息不能为空");
        }
        if($data['act'] == 'add'){
            $data['create_time'] = date('Y-m-d H:i:s',time());
            $r = M('video')->add($data);
            $this->getQrcode($r);
        }
        if($data['act'] == 'edit'){
            $r = true;
            M('video')->where(['id'=>$data['id']])->save($data);
            $this->getQrcode($data['id']);
        }



        if($r){
            $this->success("操作成功",U('admin/live/video_list'));
        }else{
            $this->error("操作失败");
        }
    }



    private function getQrcode($id)
    {
        $paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();

        $config_value = unserialize($paymentPlugin['config_value']);
        $APPID=$config_value['appid'];
        $SECRET = $config_value['appsecret'];

        $api = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$APPID}&secret={$SECRET}";
        $res=curl_get($api);
        $res = json_decode($res, true);

        if (empty($res['access_token'])) {
            return false;
        }

        $accessToken = $res['access_token'];
        $api = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";
        $curl = new Curl();
        $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
        $data = json_encode([
            'scene' => "id={$id}",
            'page' => 'pages/video_info/video_info',
            'width' => 240,
        ]);

        $curl->post($api, $data);
        if (in_array('Content-Type: image/jpeg', $curl->response_headers)) {
            //返回图片

            $json_arr = array('code'=>0,'msg'=>'获取成功','file_path'=>$this->saveTempImageByContent($curl->response,$id) );

            return 	$json_arr;
        } else {
            //返回文字
            $res = json_decode($curl->response, true);
            $json_arr = array('code'=>1,'msg'=>$res['errmsg']);

            return 	$json_arr;
        }
    }


    //保存图片内容到临时文件
    private function saveTempImageByContent($content,$id)
    {
        $save_path = QRCODE_VIDEO_PATH . '/' . md5($id) . '.jpg';
        $fp = fopen($save_path, 'w');
        fwrite($fp, $content);
        fclose($fp);
        return $save_path;
    }
}